package com.hxht.cmp.controller;

import com.github.pagehelper.Page;
import com.hxht.cmp.common.Constants;
import com.hxht.cmp.common.result.ResultResponse;
import com.hxht.cmp.entity.MajorApply;
import com.hxht.cmp.entity.MajorCase;
import com.hxht.cmp.entity.User;
import com.hxht.cmp.pojo.MajorCasePojo;
import com.hxht.cmp.pojo.MajorCaseResult;
import com.hxht.cmp.service.MajorService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author alice on 2017/8/3 0003.
 * @version 1.0
 * @since 1.0
 */
@RestController
@RequestMapping("/major")
public class MajorController {

    @Resource
    private MajorService majorService;

    @RequestMapping("/applyMajor")
    public ResultResponse applyMajor(String caseUid, String detail) {
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute("user");
        MajorApply majorApply = new MajorApply();
        majorApply.setUserUid(user.getUid());
        majorApply.setApproverDetail(detail);
        majorApply.setCaseUid(caseUid);
        majorApply.setDateCreated(new Date());
        majorApply.setLastUpdated(new Date());
        int success = majorService.insertMajorApply(majorApply);
        return success > 0 ? ResultResponse.success() : ResultResponse.failed();
    }

    @RequestMapping("/selectMajorCase")
    public ResultResponse selectMajorCase(MajorCasePojo majorCasePojo) {
        Page<MajorCase> majorCases = majorService.selectMajorCase(majorCasePojo);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < majorCases.getResult().size(); i++) {
            MajorCaseResult majorCase = new MajorCaseResult(majorCases.get(i));
            majorCase.setCreateDate(format.format(majorCases.get(i).getFilingDate()));
            majorCase.setCourtName(Constants.COURT_MAP.get(majorCase.getCourtUid()).getName());
            majorCases.set(i, majorCase);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("count", majorCases.getTotal());
        result.put("result", majorCases.getResult());
        return ResultResponse.success(result);
    }
}
